<template>
  <div class="stock-price-chart">
    <div class="chart-header">
      <div style="display: flex; align-items: center; gap: 10px;">
        <h3>{{ stockName || '股票价格曲线' }}</h3>
      </div>
      <div class="controls">
        <el-button 
          
          type="text" 
          @click="goBack"
          style="padding: 0; font-size: 16px;"
        >
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <el-select 
          v-model="selectedStock" 
          placeholder="选择股票" 
          filterable 
          clearable
          style="width: 150px; margin-right: 10px"
          @change="handleStockChange"
        >
          <el-option
            v-for="item in stockOptions"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
        
        <el-select 
          v-model="timeRange" 
          placeholder="时间范围" 
          style="width: 120px; margin-right: 10px"
          @change="handleTimeRangeChange"
        >
          <el-option label="近7天" value="7" />
          <el-option label="近30天" value="30" />
          <el-option label="近90天" value="90" />
          <el-option label="近1年" value="365" />
          <el-option label="全部" value="-1" />
        </el-select>
        
        <el-button type="primary" @click="refreshData" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
        <el-button type="success" @click="syncData" :loading="loading">
          <el-icon><Download /></el-icon>
          同步数据
        </el-button>
      </div>
    </div>

    <div class="chart-container">
      <!-- 图表容器，注意设置明确的宽高 -->
      <div ref="chartRef" style="width: 100%; height: 400px;"></div>
    </div>

    <div class="chart-info">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="info-item">
            <label>当前价格:</label>
            <span :class="{ 'up': currentPrice > yesterdayClose, 'down': currentPrice < yesterdayClose }">
              ¥{{ currentPrice.toFixed(3) }}
            </span>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="info-item">
            <label>涨跌幅:</label>
            <span :class="{ 'up': priceChange > 0, 'down': priceChange < 0 }">
              {{ priceChange > 0 ? '+' : '' }}{{ priceChange.toFixed(3) }}%
            </span>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="info-item">
            <label>最高价:</label>
            <span>¥{{ highestPrice.toFixed(3) }}</span>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="info-item">
            <label>最低价:</label>
            <span>¥{{ lowestPrice.toFixed(3) }}</span>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { Refresh, ArrowLeft, Download } from '@element-plus/icons-vue'
import { getFundFlowByDateRange, syncFundFlowData } from '../api/stockPrice'
import { getStockList } from '../api/stockTrading'

export default {
  name: 'StockPriceChart',
  components: {
    Refresh,
    ArrowLeft,
    Download
  },
  setup() {
    const chartRef = ref(null)
    // 关键修改：使用普通变量而非响应式变量存储图表实例[6,7](@ref)
    let chartInstance = null
    const loading = ref(false)
    const selectedStock = ref('')
    const timeRange = ref('-1')
    const stockName = ref('')
    const router = useRouter()
    const route = useRoute()
    
    // 股票数据
    const stockOptions = ref([])
    
    // 价格信息
    const currentPrice = ref(0)
    const yesterdayClose = ref(0)
    const priceChange = ref(0)
    const highestPrice = ref(0)
    const lowestPrice = ref(0)
    
    // 获取股票列表
    const fetchStockList = async () => {
      try {
        loading.value = true
        const response = await getStockList()
        
        if (response.code === 200 && response.data && Array.isArray(response.data)) {
          stockOptions.value = response.data.map(item => ({
            code: item.stockCode,
            name: item.stockName
          }))
          
          // 如果路由参数中有股票代码，设置为选中
          if (route.query.stockCode && stockOptions.value.length > 0) {
            const stock = stockOptions.value.find(s => s.code === route.query.stockCode)
            if (stock) {
              selectedStock.value = stock.code
              stockName.value = stock.name
            }
          }
        }
      } catch (error) {
        console.error('获取股票列表失败:', error)
        ElMessage.error('获取股票列表失败，请检查网络连接')
      } finally {
        loading.value = false
      }
    }

    // 获取股票数据
    const fetchStockData = async (stockCode, days) => {
      try {
        if (!stockCode) return []
        
        // 计算日期范围
        const endDate = new Date()
        const startDate = new Date()
        let response = null;
        if(-1 == days) {
          response = await getFundFlowByDateRange({
            stockCode: stockCode
          })
        }else {
          startDate.setDate(startDate.getDate() - days)
          response = await getFundFlowByDateRange({
            stockCode: stockCode,
            startDate: startDate.toISOString().split('T')[0],
            endDate: endDate.toISOString().split('T')[0]
          })
        }

        // 如果API没有数据，返回测试数据
        if (!response.data || response.data.length === 0) {
          return generateTestData(days)
        }
        
        // 根据API返回的数据格式处理
        if (response.code === 200 && response.data && Array.isArray(response.data)) {
          return response.data.map(item => ({
            date: item.tradeDate,
            price: parseFloat(item.closePrice),
            changeRatio: parseFloat(item.changeRatio || 0)
          })).sort((a, b) => new Date(a.date) - new Date(b.date))
        }
        
      } catch (error) {
        console.error('获取股票数据失败:', error)
        ElMessage.error('获取股票数据失败，使用模拟数据')
        return generateTestData(days)
      }
    }
    
    // 生成测试数据
    const generateTestData = (days) => {
      const data = []
      const basePrice = 10.00
      const today = new Date()
      
      for (let i = days - 1; i >= 0; i--) {
        const date = new Date(today)
        date.setDate(date.getDate() - i)
        const randomChange = (Math.random() - 0.5) * 0.1
        const price = basePrice + (Math.random() - 0.5) * 2
        const changeRatio = randomChange * 100
        
        data.push({
          date: date.toISOString().split('T')[0],
          price: Math.max(price, 1.00).toFixed(3),
          changeRatio: changeRatio.toFixed(2)
        })
      }
      
      return data
    }
    
    // 初始化图表
    const initChart = () => {
      if (!chartRef.value) return
      
      // 关键修改：直接使用普通变量存储图表实例[6,7](@ref)
      chartInstance = echarts.init(chartRef.value)
      
      // 监听窗口变化，自动调整图表大小[5](@ref)
      window.addEventListener('resize', handleResize)
    }
    
    // 更新图表数据
    const updateChartData = async () => {
      if (!chartInstance || !selectedStock.value) return
      
      try {
        loading.value = true
        // 获取股票数据
        const stockData = await fetchStockData(selectedStock.value, parseInt(timeRange.value))
        
        // 更新价格信息
        updatePriceInfo(stockData)
        
        // 准备图表数据
        const dates = stockData.map(item => item.date)
        const prices = stockData.map(item => parseFloat(item.price))
        
        // 配置项
        const option = {
          animation: false, // 禁用动画以提高性能[1](@ref)
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              crossStyle: {
                color: '#ff6b6b',
                type: 'solid'
              },
              lineStyle: {
                color: '#ff6b6b',
                type: 'solid',
                width: 1
              },
              label: {
                backgroundColor: '#ff6b6b',
                color: '#fff',
                fontSize: 11
              }
            },
            backgroundColor: 'rgba(255, 255, 255, 0.95)',
            borderColor: '#409EFF',
            borderWidth: 1,
            textStyle: {
              color: '#333',
              fontSize: 12
            },
            alwaysShowContent: false,
            triggerOn: 'none', // 禁用自动触发
            formatter: function (params) {
              // 确保params数组不为空
              if (!params || params.length === 0) return ''
              
              const dataIndex = params[0].dataIndex
              // 直接从params获取数据，避免闭包问题
              const date = params[0].axisValue
              const price = parseFloat(params[0].value)
              
              // 从原始数据中获取涨跌幅信息
              const changeRatio = stockData[dataIndex]?.changeRatio || 0
              const changeColor = changeRatio >= 0 ? '#f56c6c' : '#67c23a'
              const changeSymbol = changeRatio >= 0 ? '+' : ''
              
              // 计算价格在所有价格中的位置百分比
              const prices = stockData.map(item => parseFloat(item.price))
              const minPrice = Math.min(...prices)
              const maxPrice = Math.max(...prices)
              const pricePosition = maxPrice === minPrice ? 100 : ((price - minPrice) / (maxPrice - minPrice)) * 100
              
              // 计算与上一个价格的差值
              const prevPrice = dataIndex > 0 ? parseFloat(stockData[dataIndex - 1]?.price || 0) : price
              const priceDiff = (price - prevPrice) * 1000
              const priceDiffColor = priceDiff >= 0 ? '#f56c6c' : '#67c23a'
              const priceDiffSymbol = priceDiff >= 0 ? '+' : ''
              
              // 计算数据总天数和比当前价格高的天数
              const totalDays = stockData.length
              const higherDays = stockData.filter(item => parseFloat(item.price) > price).length
              
              return `
                <div style="font-weight: bold; margin-bottom: 5px;">${date}</div>
                <div>股价: <span style="font-weight: bold;">¥${price.toFixed(3)}</span></div>
                <div>价格位置: <span style="font-weight: bold;">${pricePosition.toFixed(1)}%</span></div>
                <div>与上日差值: <span style="color: ${priceDiffColor}; font-weight: bold;">${priceDiffSymbol}${Math.abs(priceDiff).toFixed(0)}</span></div>
                <div>涨跌幅: <span style="color: ${changeColor}; font-weight: bold;">${changeSymbol}${parseFloat(changeRatio).toFixed(2)}%</span></div>
                <div style="margin-top: 8px; padding-top: 8px; border-top: 1px solid #eee;">
                  <div style="display: flex; align-items: center; gap: 8px; margin: 4px 0;">
                    <span>📊 数据总天数:</span>
                    <span style="font-weight: bold; color: #303133; background: #f0f9ff; padding: 2px 6px; border-radius: 3px;">${totalDays}天</span>
                  </div>
                  <div style="display: flex; align-items: center; gap: 8px; margin: 4px 0;">
                    <span>📈 比当前价高:</span>
                    <span style="font-weight: bold; color: #409EFF; background: #ecf5ff; padding: 2px 6px; border-radius: 3px;">${higherDays}天</span>
                  </div>
                  <div style="display: flex; align-items: center; gap: 8px; margin: 4px 0;">
                    <span>🎯 占比:</span>
                    <span style="font-weight: bold; color: #e6a23c; background: linear-gradient(135deg, #fff5e6, #ffe4b5); padding: 3px 8px; border-radius: 12px; border: 1px solid #ffd700; box-shadow: 0 1px 3px rgba(255, 215, 0, 0.3);">${((higherDays/totalDays)*100).toFixed(1)}%</span>
                    <span style="font-size: 11px; color: #909399; padding: 1px 4px; background: #f5f7fa; border-radius: 2px;">
                      ${((higherDays/totalDays)*100) > 60 ? '📊 低位区间' : ((higherDays/totalDays)*100) > 30 ? '📈 中位区间' : '📉 高位区间'}
                    </span>
                  </div>
                </div>
              `
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: 80,
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: dates,
            axisLabel: {
              rotate: 45,
              interval: Math.floor(dates.length / 10)
            },

          },
          yAxis: {
            type: 'value',
            min: function(value) {
              return Math.floor(value.min * 10000) / 10000 - 0.0001
            },
            max: function(value) {
              return Math.ceil(value.max * 10000) / 10000 + 0.0001
            },
            axisLabel: {
              formatter: (value) => `¥${value.toFixed(3)}`
            },
            splitLine: {
              show: true,
              lineStyle: {
                type: 'dashed',
                opacity: 0.7
              }
            },
            minorTick: {
              show: true,
              splitNumber: 5
            },
            minorSplitLine: {
              show: true,
              lineStyle: {
                type: 'dotted',
                opacity: 0.3
              }
            },

          },
          series: [
            {
              name: '价格',
              type: 'line',
              data: prices,
              smooth: true,
              symbol: 'circle',
              symbolSize: 6,
              itemStyle: {
                color: '#409EFF'
              },
              lineStyle: {
                width: 2,
                color: '#409EFF'
              },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
                  { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
                ])
              }
            }
          ].concat(prices.length > 0 ? [
            {
              name: '当前价格线',
              type: 'line',
              data: new Array(prices.length).fill(currentPrice.value),
              smooth: true,
              symbol: 'none',
              lineStyle: {
                width: 2,
                color: '#ff6b6b',
                type: 'dashed'
              }
            }
          ] : []),
          graphic: prices.length > 0 ? [
            {
              type: 'text',
              right: 20,
              top: 20,
              style: {
                text: '当前: ¥' + currentPrice.value.toFixed(3),
                fill: '#ff6b6b',
                fontSize: 12,
                fontWeight: 'bold'
              }
            }
          ] : []
        }
        
        // 使用setOption更新图表
        chartInstance.setOption(option, true) // true表示不合并旧配置
        
        // 添加点击事件处理
        let isCrossShown = false
        let lastParams = null
        
        chartInstance.off('click')
        chartInstance.on('click', function(params) {
          if (params.componentType === 'series') {
            if (isCrossShown && lastParams && lastParams.dataIndex === params.dataIndex) {
              // 再次点击相同数据项，隐藏十字线
              chartInstance.dispatchAction({
                type: 'hideTip'
              })
              isCrossShown = false
              lastParams = null
            } else {
              // 点击新数据项，显示十字线
              chartInstance.dispatchAction({
                type: 'showTip',
                seriesIndex: 0,
                dataIndex: params.dataIndex
              })
              isCrossShown = true
              lastParams = params
            }
          }
        })
        
        // 增大点击触发区域 - 监听图表容器的点击事件
        chartInstance.getZr().off('click')
        chartInstance.getZr().on('click', function(event) {
          const pointInPixel = [event.offsetX, event.offsetY]
          if (chartInstance.containPixel('grid', pointInPixel)) {
            let xIndex = chartInstance.convertFromPixel('grid', pointInPixel)[0]
            // 四舍五入到最近的数据点索引
            xIndex = Math.round(xIndex)
            
            if (xIndex >= 0 && xIndex < dates.length) {
              if (isCrossShown && lastParams && lastParams.dataIndex === xIndex) {
                // 再次点击相同数据项，隐藏十字线
                chartInstance.dispatchAction({
                  type: 'hideTip'
                })
                isCrossShown = false
                lastParams = null
              } else {
                // 点击新数据项，显示十字线
                chartInstance.dispatchAction({
                  type: 'showTip',
                  seriesIndex: 0,
                  dataIndex: xIndex
                })
                isCrossShown = true
                lastParams = { dataIndex: xIndex }
              }
            }
          }
        })
      } catch (error) {
        console.error('更新图表数据失败:', error)
        ElMessage.error('图表数据更新失败')
      } finally {
        loading.value = false
      }
    }
    
    // 更新价格信息
    const updatePriceInfo = (data) => {
      if (data.length > 0) {
        const prices = data.map(item => parseFloat(item.price))
        currentPrice.value = prices[prices.length - 1]
        yesterdayClose.value = prices[prices.length - 2] || prices[prices.length - 1]
        priceChange.value = ((currentPrice.value - yesterdayClose.value) / yesterdayClose.value) * 100
        highestPrice.value = Math.max(...prices)
        lowestPrice.value = Math.min(...prices)
      }
    }
    
    // 事件处理
    const handleStockChange = () => {
      updateChartData()
    }
    
    const handleTimeRangeChange = () => {
      updateChartData()
    }
    
    const refreshData = () => {
      updateChartData()
    }
    
    // 同步数据
    const syncData = async () => {
      loading.value = true
      try {
        // 同步资金流向数据
        await syncFundFlowData()        
        ElMessage.success('数据同步成功')
        
        // 重新获取股票列表和当前选中股票的数据
        await fetchStockList()
        if (selectedStock.value) {
          await updateChartData()
        }
      } catch (error) {
        console.error('同步数据失败:', error)
        ElMessage.error('数据同步失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }
    
    // 处理窗口大小变化
    const handleResize = () => {
      if (chartInstance) {
        chartInstance.resize()
      }
    }
    
    // 返回上一页
    const goBack = () => {
      router.push('/')
    }
    
    onMounted(async () => {
      // 初始化图表
      initChart()
      
      // 获取股票列表
      await fetchStockList()
      
      // 从路由参数中获取股票信息
      if (route.query.stockCode) {
        selectedStock.value = route.query.stockCode
        const stock = stockOptions.value.find(s => s.code === route.query.stockCode)
        if (stock) {
          stockName.value = stock.name
        } else {
          stockName.value = route.query.stockName || route.query.stockCode
        }
      }
      
      // 初始更新图表数据
      if (selectedStock.value) {
        await updateChartData()
      }
    })
    
    onUnmounted(() => {
      // 清理图表实例和事件监听[6](@ref)
      if (chartInstance) {
        chartInstance.dispose()
        chartInstance = null
      }
      window.removeEventListener('resize', handleResize)
    })
    
    return {
      chartRef,
      loading,
      selectedStock,
      timeRange,
      stockOptions,
      stockName,
      currentPrice,
      yesterdayClose,
      priceChange,
      highestPrice,
      lowestPrice,
      handleStockChange,
      handleTimeRangeChange,
      refreshData,
      goBack,
      syncData
    }
  }
}
</script>

<style scoped>
.stock-price-chart {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.chart-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 500;
}

.controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.chart-container {
  width: 100%;
  margin-bottom: 20px;
}

.chart-info {
  padding: 15px;
  background: #f5f7fa;
  border-radius: 6px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}

.info-item label {
  color: #606266;
  margin-right: 8px;
}

.info-item span {
  font-weight: 500;
  color: #303133;
}

.up {
  color: #f56c6c !important;
}

.down {
  color: #67c23a !important;
}

@media (max-width: 768px) {
  .chart-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .controls {
    flex-wrap: wrap;
  }
  
  .info-item {
    margin-bottom: 10px;
  }
}
</style>